# -*- coding: utf-8 -*-
"""
用户管理API端点
包含用户CRUD操作的所有接口
"""

from typing import List
from fastapi import APIRouter, HTTPException, status
from fastapi.responses import JSONResponse

from app.models.user import User, UserCreate, UserUpdate, UserResponse
from app.services.user_service import UserService

# 创建路由器
router = APIRouter()

# 用户服务实例
user_service = UserService()


@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(user_data: UserCreate):
    """
    创建新用户
    
    Args:
        user_data: 用户创建数据
        
    Returns:
        UserResponse: 创建的用户信息
        
    Raises:
        HTTPException: 当邮箱已存在时抛出409错误
    """
    try:
        user = await user_service.create_user(user_data)
        return user
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=str(e)
        )


@router.get("/", response_model=List[UserResponse])
async def get_users():
    """
    获取所有用户列表
    
    Returns:
        List[UserResponse]: 用户列表
    """
    users = await user_service.get_all_users()
    return users


@router.get("/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
    """
    根据ID获取用户信息
    
    Args:
        user_id: 用户ID
        
    Returns:
        UserResponse: 用户信息
        
    Raises:
        HTTPException: 当用户不存在时抛出404错误
    """
    user = await user_service.get_user_by_id(user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    return user


@router.put("/{user_id}", response_model=UserResponse)
async def update_user(user_id: int, user_data: UserUpdate):
    """
    更新用户信息
    
    Args:
        user_id: 用户ID
        user_data: 更新数据
        
    Returns:
        UserResponse: 更新后的用户信息
        
    Raises:
        HTTPException: 当用户不存在时抛出404错误
    """
    user = await user_service.update_user(user_id, user_data)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    return user


@router.delete("/{user_id}")
async def delete_user(user_id: int):
    """
    删除用户
    
    Args:
        user_id: 用户ID
        
    Returns:
        dict: 删除结果信息
        
    Raises:
        HTTPException: 当用户不存在时抛出404错误
    """
    deleted_user = await user_service.delete_user(user_id)
    if not deleted_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return {
        "message": "用户删除成功",
        "deleted_user": deleted_user
    }